package cn.yotta.user.core.server.event;

import cn.yotta.user.core.server.iface.login.LoginUserContext;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @author wyaoyao
 * @date 2023/3/18 21:40
 */
@Component
@Slf4j
public class UserStatusChangeEventListener {

    private final LoginUserContext loginUserContext;

    public UserStatusChangeEventListener(LoginUserContext loginUserContext) {
        this.loginUserContext = loginUserContext;
    }

    @EventListener
    public void subscribe(UserStatusChangeEvent event) {
        try {
            switch (event.getEventType()) {
                case USER_FREEZE:
                    onFreeze(event);
                    break;
                case USER_UNFREEZE:
                    onUnFreeze(event);
                case USER_ENABLE:
                    onEnable(event);
                case USER_DISABLE:
                    onDisable(event);
                default:
                    throw new IllegalArgumentException("unknown event type");
            }
        } catch (Exception e) {
            log.error("handle UserStatusChangeEvent error; event: [{}]", event, e);
        }

    }

    protected void onDisable(UserStatusChangeEvent event) {
        // 删除这个用户的登录上下文，让其重新登录
        loginUserContext.removeContext(event.userId);
    }

    protected void onEnable(UserStatusChangeEvent event) {

    }

    protected void onUnFreeze(UserStatusChangeEvent event) {

    }

    protected void onFreeze(UserStatusChangeEvent event) {
        // 删除这个用户的登录上下文，让其重新登录
        loginUserContext.removeContext(event.getUserId());
    }

    @Getter
    @ToString
    public static class UserStatusChangeEvent {

        private final Long userId;

        private final EventType eventType;

        public UserStatusChangeEvent(Long userId, EventType eventType) {
            this.userId = userId;
            this.eventType = eventType;
        }

    }

    @AllArgsConstructor
    public static enum EventType {
        USER_FREEZE("用户被冻结"),
        USER_UNFREEZE("用户解冻"),
        USER_ENABLE("用户启用"),
        USER_DISABLE("用户被禁用"),
        ;
        private final String desc;
    }

}
